import csv
import os

from django.db.models import Q, Count
from django.http import JsonResponse
from django.shortcuts import render
from django.template.context_processors import request

from house import models, serializers
from rest_framework.views import APIView
from rest_framework.response import Response
from sklearn.metrics.pairwise import cosine_similarity

# Create your views here.

# 城市
class House_city(APIView):
    def get(self, request):
        house_city = models.House_city.objects.all()
        house_city_serializer = serializers.House_city_Serializer(house_city, many=True)
        return Response(house_city_serializer.data)


# 所有房屋
class House(APIView):
    def get(self, request):
        house = models.House.objects.all()
        house_serializer = serializers.House_Serializer(house, many=True)
        return Response(house_serializer.data)


# 房屋详情
class House_Delite(APIView):
    def get(self, request, id):
        house = models.House.objects.get(id=id)
        if house:
            house_serializer = serializers.House_Serializer(house, many=False)
            return Response(house_serializer.data)
        else:
            return Response({'msg': '没有该数据'})


#首页推荐
class HouseRecommendation(APIView):
    def get(self, request):
        user_id = request.query_params.get('user_id')  # 从请求参数中获取用户ID
        if not user_id:
            return Response({'code': 400, 'message': '缺少用户ID参数'}, status=400)

        # 获取该用户浏览过的房源记录
        user_house_records = models.User_record.objects.filter(user_id=user_id).select_related('house', 'city_pid')

        # 提取浏览过的房源ID列表以及对应的城市父类ID列表
        house_ids = [record.house.id for record in user_house_records]
        city_pid_ids = [record.city_pid.id for record in user_house_records]

        # 获取这些城市父类下被其他用户浏览过的房源记录（包含每个房源的浏览次数统计）
        popular_houses_in_city_pids = models.House.objects.filter(
            city_pid_id__in=city_pid_ids
        ).annotate(view_count=Count('user_record')).order_by('-view_count')

        # 找出其他用户浏览过但当前用户没浏览过的房源
        recommended_houses = []
        for house in popular_houses_in_city_pids:
            if house.id not in house_ids:
                recommended_houses.append(house)

        # 限制推荐房源数量为10条（可根据实际需求调整）
        recommended_houses = recommended_houses[:10]

        # 构建返回的推荐房源数据格式，这里简单返回房源标题和ID，你可以按需扩展更多字段
        result = [{'title': house.title, 'id': house.id} for house in recommended_houses]

        return Response({'code': 200, 'data': result})


#推荐高级写法
def Get_csv(request):
    data=models.User_record.objects.values('user_id','house_id')
    #指定文件夹路径
    hou_folder=os.path.join(os.getcwd(),'house')#当前项目路径下的house文件
    os.makedirs(hou_folder, exist_ok=True)#不存在则创建
    #指定文件路径
    hou_path=os.path.join(hou_folder,'user_house.csv')
    #写入csv文件
    with open(hou_path,'w',encoding='utf-8') as file:
        writer = csv.writer(file)
        #写入表头
        writer.writerow(['user_id','house_id'])
        #写入数据
        for i in data:
            writer.writerow([i['user_id'],i['house_id']])
    #返回文件存储成功响应
    return JsonResponse({'code': 200, 'message': 'CSV file saved successfully', 'path': hou_path})


from tools.services import RecommendationService
class RecommendView(APIView):
    """
    用户商品推荐视图 (基于类的视图)
    """
    # # 要求用户认证
    # permission_classes = [IsAuthenticated]

    def get(self, request, *args, **kwargs):
        """
        处理 GET 请求，根据登录用户推荐商品并返回 JSON 响应。
        """
        # 获取当前登录用户的 ID
        user_id = request.GET.get('user_id')
        user_id = int(user_id)

        # 推荐服务实例（假设 CSV 文件路径为 'doc/goods_users.csv'）
        csv_path = 'house/user_house.csv'
        recommendation_service = RecommendationService(csv_path)

        # 加载数据
        recommendation_service.load_data()

        # 获取推荐商品列表
        recommended_goods = recommendation_service.recommend_items(user_id=user_id, top_n=20)

        # 返回推荐商品作为 JSON 响应
        return Response({
            "user_id": user_id,
            "recommended_goods": recommended_goods
        })












